package com.promis.widget.paging;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;

public class PageRefreshRecyclerView extends SwipeRefreshLayout {

    private FrameLayout frameLayout;
    private RecyclerView recyclerView;
    private View emptyView;

    private OnPageScrollListener onPageScrollListener;

    public PageRefreshRecyclerView(@NonNull Context context) {
        super(context);
        init();
    }

    public PageRefreshRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        frameLayout = new FrameLayout(getContext());
        LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        this.addView(frameLayout, layoutParams);

        FrameLayout.LayoutParams frameLayoutParams = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        recyclerView = new RecyclerView(getContext());
        frameLayout.addView(recyclerView, frameLayoutParams);
    }

    public void setEmptyView(View emptyView) {
        if (emptyView == null) return;

        FrameLayout.LayoutParams frameLayoutParams = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        this.emptyView = emptyView;
        this.emptyView.setVisibility(GONE);
        frameLayout.addView(emptyView, frameLayoutParams);
    }

    public void setEmptyView(int resLayoutId) {

        this.emptyView = inflate(getContext(), resLayoutId, null);
        FrameLayout.LayoutParams frameLayoutParams = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        this.emptyView.setVisibility(GONE);
        frameLayout.addView(emptyView, frameLayoutParams);
    }

    public void notifyDisplayViewChanged() {
        if (recyclerView.getAdapter().getItemCount() == 0 && emptyView != null) {
            emptyView.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
        } else {
            emptyView.setVisibility(View.GONE);
            recyclerView.setVisibility(View.VISIBLE);
        }
    }

    public void setOnPageScrollListener(OnPageScrollListener onPageScrollListener) {
        this.onPageScrollListener = onPageScrollListener;
        this.onPageScrollListener.setSwipeRefreshLayout(this);
        recyclerView.setOnScrollListener(onPageScrollListener);
    }

    public void setPageComplete(boolean isMaxPage) {
        if (onPageScrollListener != null)
            onPageScrollListener.onRefreshComplete(isMaxPage);
    }

    public RecyclerView getRecyclerView() {
        return recyclerView;
    }
}
